/*
 * @Description: 表格加载类
 */

import { LoadMgr } from './LoadMgr';

export interface TableConfig {
  data: any; //Map<string, any>; //表格内容
  name: string; // 表格名字
}

export default class TableLoader {
  constructor(tableNames: object, callback: Function) {
    Object.keys(tableNames).forEach((key) => {
      let name = tableNames[key];
      let tc: TableConfig = {
        name: name,
        data: null,
      };
      this.tableMap[name] = tc;
    });
    this._loadedCallback = callback;
  }

  private _loadedCallback: Function;
  public tableMap: any = {}; //Map<string, TableConfig> = new Map<string, TableConfig>();    //加载的表格配置
  private _isLoaded: boolean = false;
  private _iTotalLoad: number = 0;
  private _iLoadNum: number = 0;

  async loadTableRes(): Promise<any> {
    //<Map<string, TableConfig>> {
    if (this._isLoaded) {
      return;
    }
    this._isLoaded = true;
    //await VersionMgr.inst.loadRemoteConfig();
    return new Promise((resolve) => {
      this._loadTableRes(() => {
        this._loadedCallback();
        resolve(this.tableMap);
      });
    });
  }

  private _completeCallback!: Function;
  private _loadTableRes(callback: Function): void {
    if (!this.tableMap) {
      callback();
      return;
    }
    this._completeCallback = callback;
    let keys: string[] = Object.keys(this.tableMap);
    this._iTotalLoad = keys.length;
    keys.forEach((key: string) => {
      let config = this.tableMap[key];
      if (config.name) {
        LoadMgr.loadConfig(config.name, (err, jsonAsset) => {
          config.data = jsonAsset;
          this._onInitOver();
        });
      } else {
        this._onInitOver();
      }
    });
  }

  private _onInitOver(): void {
    if (this._iLoadNum >= this._iTotalLoad) {
      console.error('资源加载数量对不上了，注意修改');
      return;
    }

    var value = this._iLoadNum / this._iTotalLoad;
    this._iLoadNum++;
    if (this._iLoadNum >= this._iTotalLoad) {
      this._completeCallback && this._completeCallback();
    }
  }
}
